package com.sg.common.empty.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.script.ScriptException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.sg.activiti.service.MyActivitiService;
import com.sg.common.empty.core.DealPermission;
import com.sg.common.empty.core.DetailBuilder;
import com.sg.common.empty.core.EditFormBuilder;
import com.sg.common.empty.core.EpUtil;
import com.sg.common.empty.core.FilterVal;
import com.sg.common.empty.core.JspUtil3;
import com.sg.common.empty.core.ListPageBuilder;
import com.sg.common.empty.core.NameValuePair;
import com.sg.common.empty.entity.PerfProperty;
import com.sg.common.empty.json.SectionDraw;
import com.sg.common.empty.json.Select;
import com.sg.common.empty.service.CfgService;
import com.sg.common.http.HttpHelper;
import com.sg.common.login.service.OrgMemberService;
import com.sg.common.utils.CollUtil;
import com.sg.common.utils.Constant;
import com.sg.common.utils.ReUtils;
import com.sg.common.utils.StrUtil;
import com.sg.common.utils.UUIDGenerator;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigList;
import com.typesafe.config.ConfigValue;

@Repository
@Controller
@RequestMapping(value = "/ut")
public class EmptyController {

	private Logger logger = LoggerFactory.getLogger(getClass());
	// final String SEPORATOR = System.getProperty("line.separator");
	@Autowired
	MyActivitiService myActivitiService;

	@Autowired
	CfgService service;

	@Autowired
	OrgMemberService omService;

	@RequestMapping(value = "/{tb}/list", method = RequestMethod.POST)
	@ResponseBody
	public Object find(HttpServletRequest request) throws Exception {
		Object listDate = null;
		String route = (String) request.getAttribute("conf.route");
		String header = (String) request.getAttribute("conf.header");

		String tableName = Constant.get(header + ".tn");

		ConfigList dataList = Constant.getList(route + ".perf.data");
		for (int i = 0; i < dataList.size(); i++) {
			Config data = dataList.get(i).atKey("data");

			boolean isICanSee = DealPermission.init(request, service,
					omService, data, "data").getCanIn();
			if (isICanSee) {
				ConfigList listPn = Constant.getList(data, "data.listPn");
				List<PerfProperty> listPl = service.emptySearches(request,
						tableName, listPn);
				ConfigList searchPn = Constant.getList(data, "data.searchPn");
				List<PerfProperty> searchPl = service.emptySearches(request,
						tableName, searchPn);
				listDate = service.emptyListDate(listPl, searchPl, request,
						service, data);
				break;
			}
		}

		return listDate;
	}

	// @RequestMapping(value = "/findAttaList", method = RequestMethod.POST)
	// @ResponseBody
	// public Object findAttaList(HttpServletRequest request) throws Exception {
	// Object beanID = request.getParameter("beanID");
	// Object className = request.getParameter("className");
	// DetachedCriteria dc = DetachedCriteria.forClass(BeanAttach.class);
	// dc.add(Restrictions.eq("beanID", beanID));
	// dc.add(Restrictions.eq("className", className));
	// dc.add(Restrictions.eq("enable", Constant.ENABLE_NOR));
	// List<BeanAttach> beanAttachs = service.find(dc);
	// JSONArray jsonData = new JSONArray();
	// for (BeanAttach ba : beanAttachs) {
	// JSONObject jo = null;
	// jo = new JSONObject();
	// jo.put("id", ba.getId());
	// jo.put("fileName", ba.getAttachment().getFileName());
	// jo.put("generateWord", ba.getAttachment().getGenerateWord());
	// jsonData.add(jo);
	// }
	// return jsonData;
	// }

	@RequestMapping(value = "/{tb}/list", method = RequestMethod.GET)
	@ResponseBody
	public Object findPage2(HttpServletRequest request) throws Exception {
		ListPageBuilder lpb = ListPageBuilder.init(request, service, omService);
		ModelAndView res = null;
		res = new ModelAndView("/jsp/common");
		res.addObject("jsHtml", lpb.listJs());
		res.addObject("bodyHtml", lpb.emptyListBody());
		EpUtil.citeMv(res, request);
		return res;
	}

	@RequestMapping(value = "/{tb}/select")
	@ResponseBody
	public Object select(HttpServletRequest request)
			throws UnsupportedEncodingException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			InstantiationException, ClassNotFoundException {
		Select select = new Select();
		if (StringUtils.equals("select2", request.getParameter("_type"))) {
			String page = request.getParameter("_page");
			if (!StrUtil.requestParamsNotEmpty(page)) {
				page = "1";
			}
			Map<String, Object> map = service.findSelect2Value(
					request.getAttribute("bean"), request.getParameter("_q"),
					request.getParameter("_fd"), page,
					request.getParameter("_rows"),
					request.getParameter("_sort"),
					request.getParameter("_order"));
			return map;
		} else if (StringUtils.equals("getValById",
				request.getParameter("_type"))) {
			return service
					.findSelectValById(request.getAttribute("bean"),
							request.getParameter("_fd"),
							request.getParameter("_idval"));
		} else {
			String route = (String) request.getAttribute("conf.route");
			List<String> params = Constant.getStringList(route + ".params");
			String sql = Constant.get(route + ".sql");
			int valueConfig = Constant.getAnyRef(route + ".value");
			List<Integer> descrsConfigs = Constant.getAnyRefList(route
					+ ".descrs");

			List<Object> sqlParams = EpUtil.transParams(service, params);
			List<String> searchs = Constant.getAnyRefList(route + ".searchPn");
			String condition = EpUtil.buildConditionSel(searchs, request);
			List<Object> dataList = service.queryBySql(
					EpUtil.replaceCondition(sql, condition),
					sqlParams.toArray());
			List<NameValuePair> nvl = new ArrayList<NameValuePair>();
			if (CollUtil.isNotEmpty(dataList)) {
				boolean validSelIndex = validSelIndex(valueConfig,
						descrsConfigs, ((Object[]) dataList.get(0)).length);
				// 验证下标不超标
				if (validSelIndex) {
					for (Object obj : dataList) {
						Object[] os = (Object[]) obj;
						NameValuePair nv = new NameValuePair();
						nv.setId((String) os[valueConfig]);
						String ts = "";
						for (int dc : descrsConfigs) {
							if (os[dc] != null) {
								ts += (String) os[dc] + " ";
							}
						}
						nv.setText(ts);
						nvl.add(nv);
					}
				} else {
					logger.error("配置文件出错");
					NameValuePair nv = new NameValuePair();
					nv.setText("配置文件出错，请联系管理员");
					nvl.add(nv);
				}
			}
			return nvl;
		}
	}

	public boolean validSelIndex(int valueConfig, List<Integer> descrsConfigs,
			int len) {
		boolean ok = true;
		if (valueConfig >= len) {
			ok = false;
		}
		if (ok) {
			for (int dc : descrsConfigs) {
				if (dc >= len) {
					ok = false;
					break;
				}
			}
		}
		return ok;
	}

	@RequestMapping(value = "/{tb}/select2")
	@ResponseBody
	public Object select2(HttpServletRequest request)
			throws UnsupportedEncodingException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		if (StringUtils.equals("select2", request.getParameter("_type"))) {
			String page = request.getParameter("_page");
			if (!StrUtil.requestParamsNotEmpty(page)) {
				page = "1";
			}
			Map<String, Object> map = service.findSelect2Value(
					request.getAttribute("bean"), request.getParameter("_q"),
					request.getParameter("_fd"), page,
					request.getParameter("_rows"),
					request.getParameter("_sort"),
					request.getParameter("_order"));

			return map;
		} else if (StringUtils.equals("getValById",
				request.getParameter("_type"))) {
			return service
					.findSelectValById(request.getAttribute("bean"),
							request.getParameter("_fd"),
							request.getParameter("_idval"));
		} else {
			List<NameValuePair> findSelectValue = service.findSelectValue(
					request.getAttribute("bean"), request.getParameter("_q"),
					request.getParameter("_fd"), request.getParameter("_sort"),
					request.getParameter("_order"));
			return findSelectValue;
		}
	}

	// @RequestMapping(value = "/{tb}/select")
	// @ResponseBody
	// public Object select(HttpServletRequest request)
	// throws UnsupportedEncodingException, IllegalAccessException,
	// InvocationTargetException, NoSuchMethodException,
	// InstantiationException, ClassNotFoundException {
	// Perf perf = (Perf) request.getAttribute("perf");
	// String layout = perf.getLayout();
	// Select select = new Select();
	// if (StringUtils.isNotEmpty(layout)) {
	// select = JSONObject.parseObject(layout, Select.class);
	// }
	// Prop[] search = select.getSearch();
	// String forDescr = select.getFordescr();
	// String sort = select.getSort();
	// String order = select.getOrder();
	//
	// List<PerfProperty> searchPl = service.searches(bean, search);
	// if (StringUtils.equals("select2", request.getParameter("_type"))) {
	// String page = request.getParameter("_page");
	// if (!StrUtil.requestParamsNotEmpty(page)) {
	// page = "1";
	// }
	// Map<String, Object> map = service.findSelect2Value(
	// request.getAttribute("bean"), request.getParameter("_q"),
	// request.getParameter("_fd"), page,
	// request.getParameter("_rows"),
	// request.getParameter("_sort"),
	// request.getParameter("_order"));
	// return map;
	// } else if (StringUtils.equals("getValById",
	// request.getParameter("_type"))) {
	// return service
	// .findSelectValById(request.getAttribute("bean"),
	// request.getParameter("_fd"),
	// request.getParameter("_idval"));
	// } else {
	// List<NameValuePair> findSelectValue = service.findSelectValue2(
	// bean, searchPl, forDescr, sort, order);
	// return findSelectValue;
	// }
	// }

	@RequestMapping(value = "/{tb}/del")
	@ResponseBody
	public Object del(HttpServletRequest request) throws Exception {
		String confHeader = (String) request.getAttribute("confHeader");
		String id = request.getParameter("_ids");
		Map<String, Object> map = new HashMap<String, Object>();
		ConfigList delPns = Constant
				.getList(confHeader + ".handler.perf.delPn");
		if (delPns != null) {
			for (int i = 0; i < delPns.size(); i++) {
				Config delPn = delPns.get(i).atKey("delPn");
				boolean isICanSee = DealPermission.init(request, service,
						omService).getCanIn();
				if (isICanSee) {
					String dSql = Constant.getT(delPn, "delPn.dSql",
							String.class);
					service.excuteBySql(dSql, new String[] { id });
					break;
				}
			}
		}
		Map<String, Object> res = new HashMap<String, Object>();
		res.put("msg", Constant.get("DEL_SUCCESS"));
		res.put("delresult", "success");
		return res;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/{tb}/get")
	@ResponseBody
	public Object detail(HttpServletRequest request) throws Exception {
		List<SectionDraw> sds = new ArrayList<SectionDraw>();
		List<PerfProperty> pps = new ArrayList<PerfProperty>();
		String route = (String) request.getAttribute("conf.route");
		String header = (String) request.getAttribute("conf.header");
		String tableName = Constant.getT(header + ".tn", String.class);
		String id = request.getParameter("id");
		Map<String, Object> map = new HashMap<String, Object>();
		ConfigList detailPns = Constant.getList(route + ".perf.detailPn");
		if (detailPns != null) {
			for (int i = 0; i < detailPns.size(); i++) {
				Config detailPn = detailPns.get(i).atKey("detailPn");
				boolean isICanSee = DealPermission.init(request, service,
						omService).getCanIn();
				if (isICanSee) {
					String title = Constant.getT(detailPn, "detailPn.title",
							String.class);
					if (StringUtils.isEmpty(title))
						title = "详细";
					String bk = Constant.getT(detailPn, "detailPn.bk",
							String.class);
					ConfigList pnsConfig = Constant.getList(detailPn,
							"detailPn.pns");
					SectionDraw sd = new SectionDraw();
					List<PerfProperty> searches = service.emptySearches(
							request, tableName, pnsConfig);
					sd.setPps(searches);
					pps.addAll(searches);
					sd.setTitle(title);
					sd.setBk(bk);
					sds.add(sd);
					String qSql = Constant.getT(detailPn, "detailPn.qSql",
							String.class);
					String findData = "";
					List<String> listData = new ArrayList<String>();
					Iterator<ConfigValue> config = pnsConfig.iterator();
					while (config.hasNext()) {
						ConfigValue configValue = (ConfigValue) config.next();
						Map<String, String> config2 = (Map<String, String>) configValue
								.unwrapped();
						String pnx = config2.get("pn");
						String alias = config2.get("alias");
						String[] pns = StringUtils.split(pnx, ",");
						for (String pn : pns) {
							if (StringUtils.isNotEmpty(alias))
								findData = findData + pn + " as " + alias + ",";
							else {
								if (pn.contains("."))
									findData = findData + pn + ",";
								else
									findData = findData + tableName + "." + pn
											+ ",";
							}
							listData.add(pn);
						}
					}
					findData = findData.substring(0, findData.length() - 1);
					List<Object> dataList = service.queryBySql("select "
							+ findData + " " + qSql, new String[] { id });

					if (dataList.size() > 0) {
						Object obj = dataList.get(0);
						int j = 0;
						for (String p : listData) {
							String[] ps = StringUtils.split(p, ".");
							if (ps.length > 1) {
								Map<String, Object> childMap = (Map<String, Object>) map
										.get(ps[0]);
								if (childMap == null)
									childMap = new HashMap<String, Object>();
								ReUtils.set(childMap, ps[1],
										((Object[]) obj)[j]);
								ReUtils.set(map, ps[0], childMap);
							} else {
								ReUtils.set(map, p, ((Object[]) obj)[j]);
							}
							j++;
						}
					}
					break;
				}
			}
		}
		StringBuilder js = new StringBuilder();

		DetailBuilder db = new DetailBuilder();
		db.init(request);
		db.setMap(map);
		db.setSds(sds);
		StringBuilder body = db.emptyNdetail();

		return EpUtil.commonView(body, js, request);
	}

	// @RequestMapping(value = "/{tb}/tree")
	// @ResponseBody
	// public Object tree(HttpServletRequest request) throws SQLException,
	// NoSuchFieldException, IllegalAccessException,
	// InvocationTargetException, NoSuchMethodException {
	// List<String> endToTopPathIds = service.endToTopPathIds(
	// request.getParameter("_endTreeValue"),
	// request.getAttribute("bean"));
	// List<String> descrs = EpUtil.findDescrPropertyByFd(request
	// .getParameter("_fd"));
	// String id = request.getParameter("id");
	// if (!StrUtil.requestParamsNotEmpty(id)) {
	// id = request.getParameter("_id");
	// }
	// return service.findTreeValue(request.getAttribute("bean"), id,
	// endToTopPathIds, descrs);
	// }

	@RequestMapping(value = "/{tb}/edit", method = RequestMethod.GET)
	@ResponseBody
	public Object editPage(HttpServletRequest request)
			throws NoSuchFieldException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			IllegalArgumentException, SecurityException,
			ClassNotFoundException, InstantiationException, ServletException,
			IOException {

		List<SectionDraw> sds = new ArrayList<SectionDraw>();
		List<PerfProperty> pps = new ArrayList<PerfProperty>();

		String route = (String) request.getAttribute("conf.route");
		String header = (String) request.getAttribute("conf.header");
		String tableName = Constant.getT(header + ".tn", String.class);
		String id = request.getParameter("id");
		Map<String, Object> map = new HashMap<String, Object>();
		ConfigList editPns = Constant.getList(route + ".perf.editPn");
		if (editPns != null) {
			for (int i = 0; i < editPns.size(); i++) {
				Config editPn = editPns.get(i).atKey("editPn");
				boolean isICanSee = DealPermission.init(request, service,
						omService, editPn, "editPn").getCanIn();
				if (isICanSee) {
					String title = Constant.getT(editPn, "editPn.title",
							String.class);
					if (StringUtils.isEmpty(title))
						title = "修改";
					String bk = Constant
							.getT(editPn, "editPn.bk", String.class);
					ConfigList props = Constant.getList(editPn, "editPn.props");
					SectionDraw sd = new SectionDraw();
					List<PerfProperty> searches = service.emptySearches(
							request, tableName, props);
					sd.setPps(searches);
					pps.addAll(searches);
					sd.setTitle(title);
					sd.setBk(bk);
					sds.add(sd);
					String tSql = Constant.getT(editPn, "editPn.qSql",
							String.class);
					String findData = "";
					List<String> listData = new ArrayList<String>();

					for (int j = 0; j < props.size(); j++) {
						Config propsValue = props.get(j).atKey("props");
						String pnx = Constant.get(propsValue, "props.pn");
						String alias = Constant.get(propsValue, "props.alias");
						String[] pns = StringUtils.split(pnx, ",");
						for (String pn : pns) {
							if (StringUtils.isNotEmpty(alias))
								findData = findData + pn + " as " + alias + ",";
							else {
								if (pn.contains("."))
									findData = findData + pn + ",";
								else
									findData = findData + tableName + "." + pn
											+ ",";
							}
							listData.add(pn);
						}
					}
					findData = findData.substring(0, findData.length() - 1);
					List<Object> dataList = service.queryBySql("select "
							+ findData + " " + tSql, new String[] { id });

					if (dataList.size() > 0) {
						Object obj = dataList.get(0);
						int j = 0;
						for (String p : listData) {
							String[] ps = StringUtils.split(p, ".");
							if (ps.length > 1) {
								Map<String, Object> childMap = (Map<String, Object>) map
										.get(ps[0]);
								if (childMap == null)
									childMap = new HashMap<String, Object>();
								ReUtils.set(childMap, ps[1],
										((Object[]) obj)[j]);
								ReUtils.set(map, ps[0], childMap);
							} else {
								ReUtils.set(map, p, ((Object[]) obj)[j]);
							}
							j++;
						}
					}
					break;
				}
			}
		}

		StringBuilder js = new StringBuilder();
		js.append(JspUtil3.findSaveSubmitJs());

		EditFormBuilder efb = new EditFormBuilder();
		efb.init(request);
		efb.setMap(map);
		efb.setRoute(route);
		efb.setActiService(myActivitiService);
		efb.setSds(sds);
		StringBuilder body = efb.emptyNeditForm();

		return EpUtil.commonView(body, js, request);

	}

	@RequestMapping(value = "/{tb}/edit", method = RequestMethod.POST)
	@ResponseBody
	public Object edit(HttpServletRequest request) throws NoSuchFieldException,
			IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, IllegalArgumentException, SecurityException,
			ClassNotFoundException, InstantiationException, ScriptException,
			ServletException, IOException {

		String route = (String) request.getAttribute("conf.route");
		String id = request.getParameter("id");
		if (Constant.hasPath(route + ".perf.editPn")) {
			ConfigList editPns = Constant.getList(route + ".perf.editPn");
			for (int i = 0; i < editPns.size(); i++) {

				Config editPn = editPns.get(i).atKey("editPn");
				boolean isICanSee = DealPermission.init(request, service,
						omService, editPn, "editPn").getCanIn();
				if (isICanSee) {
					String sql = Constant.getT(editPn, "editPn.uSql",
							String.class);
					List<String> sqlParams = new ArrayList<String>();
					List<String> params = Constant.getStringList(editPn,
							"editPn.params");
					for (String param : params) {
						String beanValue = "";
						if (param.startsWith(":")) {
							beanValue = (String) FilterVal.init(param, service)
									.get();
						} else {
							beanValue = request.getParameter(param);
						}
						sqlParams.add(beanValue);
					}
					sqlParams.add(id);
					service.excuteBySql(sql, sqlParams.toArray());
					break;
				}
			}
		}
		return EpUtil.createBlankMv(Constant.get("UPDATE_SUCCESS"));

	}

	// private Object createMsgMap(String string) {
	// Map hashMap = new HashMap();
	// hashMap.put("msg", string);
	// return hashMap;
	// }

	// @RequestMapping(value = "/{tb}/batchEdit", method = RequestMethod.GET)
	// @ResponseBody
	// public Object batchEditPage(HttpServletRequest request)
	// throws NoSuchFieldException, IllegalAccessException,
	// InvocationTargetException, NoSuchMethodException,
	// IllegalArgumentException, SecurityException,
	// ClassNotFoundException, InstantiationException {
	//
	// Perf perf = (Perf) request.getAttribute("perf");
	// // @SuppressWarnings("unchecked")
	// // List<Permission> specialPermission = (List<Permission>) request
	// // .getAttribute("specialPermission");
	// String kind = perf.getKind();
	// String layout = perf.getLayout();
	// String _editids = request.getParameter("_editids");
	// Object bean = request.getAttribute("bean");
	// Object tableBean = request.getAttribute("tableBean");
	// AssertUtils.notNull(bean, "更新对象不能为空");
	// if (!StrUtil.requestParamsNotEmpty(_editids)
	// || _editids.split(",").length == 1) {
	//
	// String userCode = (String) request.getSession().getAttribute(
	// Constant.SESSION_MEMBER_CODE);
	// if (StringUtils.equals("1", ReUtils.getStr(tableBean, "isFlow"))
	// && !myActivitiService.flowFilter(bean, userCode)) {
	// ModelAndView modelAndView = new ModelAndView(
	// "redirect:/cfg/common/403");
	// modelAndView.getModel().put("errMsg", "errCode:2578605");
	// return modelAndView;
	// }
	// // 单条更新
	// if (StringUtils.equals("nedit", kind)) {// 普通单条更新
	// Nsecs ne = JSON.parseObject(layout, Nsecs.class);
	// String enctype = ne.getEnctype();
	// SecTable[] sts = ne.getSts();
	// SecList[] sls = ne.getSls();
	// List<SectionDraw> sds = new ArrayList<SectionDraw>();
	// List<PerfProperty> searches = new ArrayList<PerfProperty>();
	// for (SecTable st : sts) {
	// SectionDraw sd = new SectionDraw();
	// searches = service.searches(bean, st.getProps());
	// sd.setPps(searches);
	// PropertyUtils.copyProperties(sd, st);
	// sds.add(sd);
	// }
	// service.buildPropertyShowValueForEdit(bean, searches);
	//
	// StringBuilder js = new StringBuilder();
	// js.append(JspUtil3.findSaveSubmitJs());
	// EditFormBuilder efb = new EditFormBuilder();
	// efb.init(request);
	// efb.setEnctype(enctype);
	// efb.setActiService(myActivitiService);
	// efb.setSds(sds);
	// efb.setSls(sls);
	// StringBuilder body = efb.neditForm();
	//
	// return EpUtil.commonView(body, js, request);
	// } else if (StringUtils.equals("mutiedit", kind)) {// 复杂页面更新
	// Nsecs ne = JSON.parseObject(layout, Nsecs.class);
	// String enctype = ne.getEnctype();
	// SecTable[] sts = ne.getSts();
	// SecList[] sls = ne.getSls();
	// MutiTable[] sms = ne.getSms();
	// List<SectionDraw> sds = new ArrayList<SectionDraw>();
	// List<PerfProperty> searches = new ArrayList<PerfProperty>();
	// for (SecTable st : sts) {
	// SectionDraw sd = new SectionDraw();
	// searches = service.searches(bean, st.getProps());
	// sd.setPps(searches);
	// PropertyUtils.copyProperties(sd, st);
	// sds.add(sd);
	// }
	// service.buildPropertyShowValueForEdit(bean, searches);
	// List<SectionListDraw> slds = new ArrayList<SectionListDraw>();
	// for (MutiTable sm : sms) {
	// String refClass = sm.getRefClass();
	// List<PerfProperty> smpps = service.searches(
	// Class.forName(refClass).newInstance(),
	// sm.getProps());
	// SectionListDraw sld = new SectionListDraw();
	// sld.setPps(smpps);
	// PropertyUtils.copyProperties(sld, sm);
	// slds.add(sld);
	// }
	// StringBuilder js = new StringBuilder();
	// js.append(JspUtil3.findSaveSubmitJs());
	// EditFormBuilder efb = new EditFormBuilder();
	// efb.init(request);
	// efb.setEnctype(enctype);
	// efb.setSds(sds);
	// efb.setSls(sls);
	// efb.setService(service);
	// efb.setActiService(myActivitiService);
	// efb.setSlds(slds);
	// StringBuilder body = efb.neditForm();
	//
	// return EpUtil.commonView(body, js, request);
	// }
	// } else {// 多条更新
	// String[] editids = _editids.split(",");
	// Nsecs ne = JSON.parseObject(layout, Nsecs.class);
	// String enctype = ne.getEnctype();
	// SecTable[] sts = ne.getSts();
	// List<PerfProperty> searches = new ArrayList<PerfProperty>();
	// List<SectionDraw> sds = new ArrayList<SectionDraw>();
	// for (SecTable st : sts) {
	// searches.addAll(service.searches(bean, st.getProps()));
	// SectionDraw sd = new SectionDraw();
	// PropertyUtils.copyProperties(sd, st);
	// sd.setPps(searches);
	// sds.add(sd);
	// }
	// List<Object> listBean = new ArrayList<Object>();
	// for (String id : editids) {
	// Object object = null;
	// if (bean instanceof Map) {
	// Map beanMap = (Map) bean;
	// String className = (String) beanMap.get(Constant.BEAN_TYPE);
	// object = service.get(className, id);
	// } else {
	// object = service.get(bean.getClass(), id);
	// }
	// listBean.add(object);
	// }
	// StringBuilder js = new StringBuilder();
	// js.append(JspUtil3.findSaveSubmitJs());
	// EditFormBuilder efb = new EditFormBuilder();
	// efb.init(request);
	// efb.setEnctype(enctype);
	// efb.setSds(sds);
	// efb.setListBean(listBean);
	// StringBuilder body = efb.seditForm();
	//
	// return EpUtil.commonView(body, js, request);
	// }
	// return EpUtil.showSpecialButtons(perf, request);
	//
	// }

	@RequestMapping(value = "/{tb}/add", method = RequestMethod.GET)
	@ResponseBody
	public Object addPage(HttpServletRequest request)
			throws NoSuchFieldException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			IllegalArgumentException, SecurityException,
			ClassNotFoundException, InstantiationException, ServletException,
			IOException {
		List<SectionDraw> sds = new ArrayList<SectionDraw>();
		List<PerfProperty> pps = new ArrayList<PerfProperty>();
		getByPerf(request, sds, pps);

		StringBuilder js = new StringBuilder();
		js.append(JspUtil3.findSaveSubmitJs());
		StringBuilder body = new StringBuilder();
		body.append(JspUtil3.emptynaddForm(request, sds));
		ModelAndView res = EpUtil.commonView(body, js, request);

		return res;
	}

	public void getByPerf(HttpServletRequest request, List<SectionDraw> sds,
			List<PerfProperty> pps) throws ServletException, IOException,
			IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, InstantiationException,
			ClassNotFoundException {
		String route = (String) request.getAttribute("conf.route");
		String header = (String) request.getAttribute("conf.header");
		if (Constant.hasPath(route + ".perf.addPn")) {
			String tableName = Constant.getT(header + ".tn", String.class);
			ConfigList addPns = Constant.getList(route + ".perf.addPn");
			for (int i = 0; i < addPns.size(); i++) {
				Config addPn = addPns.get(i).atKey("addPn");
				boolean isICanSee = DealPermission.init(request, service,
						omService, addPn, "addPn").getCanIn();
				if (isICanSee) {
					String title = Constant.getT(addPn, "addPn.title",
							String.class);
					if (StringUtils.isEmpty(title))
						title = "新增";
					String bk = Constant.getT(addPn, "addPn.bk", String.class);
					ConfigList props = Constant.getList(addPn, "addPn.props");
					SectionDraw sd = new SectionDraw();
					List<PerfProperty> searches = service.emptySearches(
							request, tableName, props);
					sd.setPps(searches);
					pps.addAll(searches);
					sd.setTitle(title);
					sd.setBk(bk);
					sds.add(sd);
					break;
				}
			}
		}
	}

	@RequestMapping(value = "/{tb}/add", method = RequestMethod.POST)
	@ResponseBody
	public Object add(HttpServletRequest request) throws NoSuchFieldException,
			IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, IllegalArgumentException, SecurityException,
			ClassNotFoundException, InstantiationException, SQLException {

		String route = (String) request.getAttribute("conf.route");

		if (Constant.hasPath(route + ".perf.addPn")) {
			ConfigList addPns = Constant.getList(route + ".perf.addPn");
			for (int i = 0; i < addPns.size(); i++) {

				Config addPn = addPns.get(i).atKey("addPn");
				String sql = Constant.getT(addPn, "addPn.sql", String.class);
				List<String> sqlParams = new ArrayList<String>();
				List<String> params = Constant.getStringList(addPn,
						"addPn.params");
				sqlParams.add(new UUIDGenerator().generate().toString());
				for (String param : params) {
					String beanValue = "";
					if (param.startsWith(":")) {
						beanValue = (String) FilterVal.init(param, service)
								.get();
					} else {
						beanValue = request.getParameter(param);
					}
					sqlParams.add(beanValue);
				}
				service.excuteBySql(sql, sqlParams.toArray());
			}
		}
		return "succ";
	}

	@RequestMapping(value = "/{tb}/confirm")
	@ResponseBody
	public String confirm(HttpServletRequest request) {
		Map<String, String> mip = new HashMap<String, String>();

		String code = request.getParameter("code");
		String psd = request.getParameter("psd");

		mip.put("code", code);
		mip.put("psd", psd);

		JSONObject httpRes = HttpHelper.httpPost(Constant.get("checkpsd"), mip);
		if (httpRes != null
				&& StringUtils.equals(httpRes.getString("errmsg"), "ok"))
			return "true";
		else
			return "false";
	}

	/**
	 * 返回错误页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/{tb}/403")
	@ResponseBody
	public Object to403(HttpServletRequest request) {
		ModelAndView res = new ModelAndView("/jsp/403");
		res.addObject("errMsg", request.getParameter("errMsg"));
		return res;
	}

}